<?php
/**
 * @file indigo/framework/classes/Router.php
 * Contains definition of the Router class
 */

  namespace indigo\framework;

 /**
  * @class Router
  * Responsible for determining which module to execute for a given request
  */
  class Router
  {
   /**
    * Contains mappings of request variables and modules
    *
    * Members of this array have keys that when compared with the first part of the $_GET['action'] variable, maps to the fully qualified name of the module
    * @see Line 31 of Router.php
    */
    private $_mappings = array();

   /**
    * @todo Implement the Router constructor to extend the Router::$_mappings
    */
    public function __construct()
    {
      // extend mappings
    }

   /**
    * Interprets the user request and execute the corresponding module
    *
    * Extracts arguments from the $_GET['action'] variable by using PHP explode() on it.
    * Tries to load the proper module for the request based on the first member of the exploded array.
    * Then executes the module using the remaining members of the exploded array as arguments
    *
    * @param $request An instance of the Request class
    * @returns the return value of the Module::execute() method when called, 
    *          or false if there was an error (see ModuleFactory::load errors, or #$_mappings contained a class that is not a subclass of Module)
    * @see ModuleFactory::load() for possible errors
    */
    public function dispatch(Request $request)
    {
			$args = explode('/' , $request->get('action'));

      if (($moduleName = $this->_mappings[$args[0]]) !== NULL) {
				// assume that the first argument refers to the module name
				array_shift($args); // we're done processing the first argument
      }
			else {
				// else, assume that we are using the site's default module and the first argument is the content type that will be processed later
				$moduleName = 'indigo\cms\CMS';
      }

			$module = ModuleFactory::load($moduleName);

      // module factory returns the instance of the module if there are no errors
      if (is_subclass_of($module, 'indigo\framework\Module')) {
        return $module->execute($args);
      } else {
        return false;
      }
    }
  }